package com.googlecode.bip.servlet;

import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// On maven, add:
//<dependency>   
//<groupId>net.sf.json-lib</groupId>   
//<artifactId>json-lib</artifactId>   
//<version>2.1</version>   
//<classifier>jdk15</classifier>   
//</dependency>  
//<dependency>
// <groupId>xom</groupId>
// <artifactId>xom</artifactId>
// <version>1.2.5</version>
//</dependency>
//import net.sf.json.JSON;
//import net.sf.json.xml.XMLSerializer;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class FileUploadHttpServletXmlToJson extends HttpServlet {
	private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response
            )
    throws ServletException, IOException
    {
    	//PrintWriter out = response.getWriter();
   	 	
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
        	// Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Parse the request
            try {
    	        FileItemIterator iter = upload.getItemIterator(request);
    	        while (iter.hasNext()) {
    	            FileItemStream item = iter.next();
    	            String name = item.getFieldName();
    	            InputStream stream = item.openStream();
    	            if (item.isFormField()) {
    	                System.out.println("Form field " + name + " with value "
    	                    + Streams.asString(stream) + " detected.");
    	            } else {
    	                System.out.println("File field " + name + " with file name "
    	                    + item.getName() + " detected.");
    	                // Process the input stream
    	                
    	                /*XMLSerializer xmlSerializer = new XMLSerializer(); 
    	                JSON json = xmlSerializer.readFromStream(item.openStream());
    	                out.println(json.toString());*/
    	            }
    	        }
            } catch( FileUploadException e ) {
                throw new ServletException( e );
            }
        }
        
        
        
    }
}
